package org.jeecg.modules.demo.mpwlwjc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.demo.mpwlwjc.entity.ZwglMpsbsj;
import org.jeecg.modules.demo.mpwlwjc.mapper.ZwglMpsbsjMapper;
import org.jeecg.modules.demo.mpwlwjc.service.IZwglMpsbsjService;
import org.jeecg.modules.demo.sjtjfx.entity.ZwglMpwdfx;
import org.jeecg.modules.demo.sjtjfx.entity.ZwglWsgz;
import org.jeecg.modules.demo.sjtjfx.mapper.ZwglMpwdfxMapper;
import org.jeecg.modules.demo.sjtjfx.mapper.ZwglWsgzMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Description: 苗棚设备数据
 * @Author: jeecg-boot
 * @Date: 2023-04-17
 * @Version: V1.0
 */
@Service
public class ZwglMpsbsjServiceImpl extends ServiceImpl<ZwglMpsbsjMapper, ZwglMpsbsj> implements IZwglMpsbsjService {
    @Autowired
    private ZwglDpsblistServiceImpl zwglDpsblistService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ZwglMpsbsjMapper zwglMpsbsjMapper;
    @Autowired
    private ZwglMpwdfxMapper zwglMpwdfxMapper;
    @Autowired
    private ZwglWsgzMapper zwglWsgzMapper;

    @Override
    public String getMpsj() {
        long l = System.currentTimeMillis();
        //new日期对象
        Date date = new Date(l);
        //转换提日期输出格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = dateFormat.format(date);
        //调用的api的接口地址

        String apiPath = "https://agro-iot.auto-control.com.cn/api/latest-data";
        BufferedReader in = null;
        StringBuffer result = null;
        String token = (String) redisUtil.get("mptoken");
        if (Objects.isNull(token)) {
            zwglDpsblistService.getToken();
        }

        try {
            URL url = new URL(apiPath);
            //打开和url之间的连接

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);


            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", token);
            connection.setRequestProperty("Charset", "utf-8");
            connection.connect();
            result = new StringBuffer();
            //读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            String result2 = result.toString(); //返回json字符串

            //获取数据
            JSONObject jsonObject = JSON.parseObject(result2);

            JSONArray jsonArray = jsonObject.getJSONArray("data");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                String a = jsonObject1.getString("deviceTypeId");
                if (a.equals("C001")) {
                    JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                    JSONArray jsonArray1 = jsonObject2.getJSONArray("data");
                    ZwglMpsbsj zwglMpsbsj = new ZwglMpsbsj();
                    zwglMpsbsj.setSbmc(jsonObject2.getString("stationName"));
                    zwglMpsbsj.setCgqbh(jsonObject2.getString("deviceId"));
                    zwglMpsbsj.setKqwd(jsonArray1.getJSONObject(0).getString("value"));
                    zwglMpsbsj.setKqsd(jsonArray1.getJSONObject(1).getString("value"));
                    zwglMpsbsj.setGz(jsonArray1.getJSONObject(2).getString("value"));
                    zwglMpsbsj.setEyhtnd(jsonArray1.getJSONObject(3).getString("value"));
                    zwglMpsbsj.setTrwd(jsonArray1.getJSONObject(4).getString("value"));
                    zwglMpsbsj.setTrsd(jsonArray1.getJSONObject(5).getString("value"));
                    zwglMpsbsj.setSj(new Date());
                    zwglMpsbsjMapper.insert(zwglMpsbsj);
                } else {

                }


            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    @Override
    public String zuigao() {
        String[] arr;
        arr = new String[6];
        arr[0] = "温室#1";
        arr[1] = "温室#2";
        arr[2] = "温室#3";
        arr[3] = "温室#4";
        arr[4] = "温室#5";
        arr[5] = "温室#6";

        for (int i = 0; i < arr.length; i++) {
            QueryWrapper<ZwglMpsbsj> queryWrapper = new QueryWrapper<>();
            /**
             * 字符串类型的数字排大小
             */
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String time = dateFormat.format(date);

            /**
             * 最高温度
             */
            queryWrapper.orderByDesc("CAST(kqwd AS UNSIGNED)");
            queryWrapper.eq("sbmc", arr[i]);
            queryWrapper.like("sj", time);
            queryWrapper.last("LIMIT 1");
            List<ZwglMpsbsj> list = zwglMpsbsjMapper.selectList(queryWrapper);
            ZwglMpwdfx zwglMpwdfx = new ZwglMpwdfx();
            zwglMpwdfx.setZgwd(list.get(0).getKqwd());
            zwglMpwdfx.setSj(list.get(0).getSj());
            zwglMpwdfx.setMpmc(list.get(0).getSbmc());
            /**
             * 最低温度
             */
            QueryWrapper<ZwglMpsbsj> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.orderByAsc("CAST(kqwd AS UNSIGNED)");
            queryWrapper1.eq("sbmc", arr[i]);
            queryWrapper1.like("sj", time);
            queryWrapper1.last("LIMIT 1");
            List<ZwglMpsbsj> list1 = zwglMpsbsjMapper.selectList(queryWrapper1);
            zwglMpwdfx.setZdwd(list1.get(0).getKqwd());
            /**
             * 平均温度
             */
            QueryWrapper<ZwglMpsbsj> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("sbmc", arr[i]);
            queryWrapper2.like("sj", time);
            queryWrapper2.select("avg(CAST(kqwd AS SIGNED)) as pjkqwd");
            List<ZwglMpsbsj> list2 = zwglMpsbsjMapper.selectList(queryWrapper2);
            zwglMpwdfx.setPjwd(list2.get(0).getPjkqwd().toString());
            /**
             * 最高土壤湿度
             */
            QueryWrapper<ZwglMpsbsj> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.orderByDesc("CAST(trsd AS UNSIGNED)");
            queryWrapper3.eq("sbmc", arr[i]);
            queryWrapper3.like("sj", time);
            queryWrapper3.last("LIMIT 1");
            List<ZwglMpsbsj> list3 = zwglMpsbsjMapper.selectList(queryWrapper3);
            zwglMpwdfx.setTrzgsd(list3.get(0).getTrsd());
            /**
             * 最低土壤湿度
             */
            QueryWrapper<ZwglMpsbsj> queryWrapper4 = new QueryWrapper<>();
            queryWrapper4.orderByAsc("CAST(trsd AS UNSIGNED)");
            queryWrapper4.eq("sbmc", arr[i]);
            queryWrapper4.like("sj", time);
            queryWrapper4.last("LIMIT 1");
            List<ZwglMpsbsj> list4 = zwglMpsbsjMapper.selectList(queryWrapper4);
            zwglMpwdfx.setTrzdsd(list4.get(0).getTrsd());
            zwglMpwdfxMapper.insert(zwglMpwdfx);
        }


        return "ok";

    }

    @Override
    public String pjguangzhao() {
        String[] arr1;
        arr1 = new String[6];
        arr1[0] = "温室#1";
        arr1[1] = "温室#2";
        arr1[2] = "温室#3";
        arr1[3] = "温室#4";
        arr1[4] = "温室#5";
        arr1[5] = "温室#6";

        for (int i = 0; i < arr1.length; i++) {
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String time = dateFormat.format(date);
            QueryWrapper<ZwglMpsbsj> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("sbmc", arr1[i]);
            queryWrapper.like("sj", time);
            queryWrapper.select("avg(CAST(gz AS SIGNED)) as pjgzd");
            List<ZwglMpsbsj> list = zwglMpsbsjMapper.selectList(queryWrapper);
            ZwglWsgz zwglWsgz = new ZwglWsgz();
            zwglWsgz.setPjgz(list.get(0).getPjgzd());
            zwglWsgz.setSj(date);
            QueryWrapper<ZwglMpsbsj> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.like("sbmc", arr1[i]);
            List<ZwglMpsbsj> list1 = zwglMpsbsjMapper.selectList(queryWrapper1);
            zwglWsgz.setWsmc(list1.get(0).getSbmc());
            zwglWsgzMapper.insert(zwglWsgz);


        }


        return "ok";

    }


    @Override
    public Result getmpmcsj(String sbmc) {
        return Result.OK(zwglMpsbsjMapper.getLatestDataForDevice(sbmc));

    }


    @Override
    public Result getdapengshijian(String kaishishijian, String jieshushijian, String sbmc) {
        // 格式化开始和结束时间
        String formattedKaishishijian = kaishishijian + " 00:00:00";
        String formattedJieshushijian = jieshushijian + " 23:59:59";

        // 调用 MyBatis 映射器接口的方法
        List<ZwglMpsbsj> list = zwglMpsbsjMapper.selectByCondition(formattedKaishishijian, formattedJieshushijian, sbmc);

        // 返回结果
        return Result.OK(list);
    }

    @Override
    public Result miaopengshijian(String starttime, String endtime, String sbmc, Integer pageNo) {
        QueryWrapper<ZwglMpsbsj> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("sj", starttime, endtime);
        queryWrapper.eq("sbmc", sbmc);
        Page<ZwglMpsbsj> page = new Page<>(pageNo, 10);
        Page<ZwglMpsbsj> list = zwglMpsbsjMapper.selectPage(page, queryWrapper);
        return Result.OK(list);

    }

}
